<template>
    <van-form @submit="onSubmit">
        <van-field v-if="editUser.editName === '性别'" v-model="editUser.currentValue as string"
            :name="editUser.editKey as string" :label="editUser.editName as string"
            :placeholder="`请输入${editUser.editName}`" />
        <van-field name="logo" label="头像" v-else-if="editUser.editName === '头像'">
            <template #input>
                <van-uploader v-model="fileList" multiple :max-count="1" />
            </template>
        </van-field>
        <van-field v-else v-model="editUser.currentValue as string" :name="editUser.editKey as string"
            :label="editUser.editName as string" :placeholder="`请输入${editUser.editName}`" />

        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                确认修改
            </van-button>
        </div>
    </van-form>

</template>

<script setup lang="ts">
import { getCurrentUser } from '@/services/user';
import { ImageToBase64 } from '@/utils/ImgToBase64';
import request from '@/utils/axios';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute()
const router = useRouter()
const fileList = ref([])
const editUser = ref({
    editKey: route.query.editKey,
    editName: route.query.editName,
    currentValue: route.query.currentValue
})
if (editUser.value.editName === "性别") {
    editUser.value.currentValue = editUser.value.currentValue === '1' ? '男' : '女'
}

const onSubmit = async () => {
    const loginUser = await getCurrentUser()
    if (editUser.value.editKey === 'gender') {
        editUser.value.currentValue = editUser.value.currentValue === '男' ? '1' : '0'
    }
    
    if(editUser.value.editKey === 'avatarUrl'){
       editUser.value.currentValue = await ImageToBase64(fileList.value[0])
    }
    const res = await request.post('/user/update', {
        'id': loginUser.id,
        [editUser.value.editKey as string]: editUser.value.currentValue,
    })

    if (res.data > 0) {
        //@ts-ignore
        showSuccessToast('修改成功');
        router.back()
    } else {
        //@ts-ignore
        showSuccessToast('修改失败');
    }
}

</script>